﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Sirenix.OdinInspector;

[DisallowMultipleComponent]
public class TextLocalizer : Localizer
{
    public string key;

    Text text;

    [ShowInInspector, ReadOnly]
    string defaultText;
    [ShowInInspector, ReadOnly]
    string lastLocalizedText;

    [ShowInInspector, ReadOnly]
    public bool IsChangedByOutter
    {
        get
        {
            return this.text.text != this.defaultText && this.text.text != this.lastLocalizedText;
        }
    }

    void Awake()
    {
        var text = this.GetComponent<Text>();
        this.text = text;
        if(text != null)
        {
            this.defaultText = text.text;
        }
    }

    bool HasTextComponent
    {
        get
        {
            if (text != null)
            {
                return true;
            }
            return false;
        }
    }

    public void Set(string key)
    {
        this.key = key;
        this.SetDirty();
    }

    protected override void Refresh()
    {
        var hasTextComponent = this.HasTextComponent;
        if (!hasTextComponent)
        {
            return;
        }
        if(string.IsNullOrEmpty(this.key))
        {
            return;
        }

        if(this.IsChangedByOutter)
        {
            // text 内容已经被外部修改，禁用本地化
            return;
        }

        //if(this.key == "$GalleryJiajuPageV2_$text_name_738ebc5b48f512525a5364a370343310")
        //{
        //    Debug.Log("$GalleryJiajuPageV2_$text_name_738ebc5b48f512525a5364a370343310");
        //}

        string msg = LocalizationManager.Stuff.TryLocalize(this.defaultText, this.key);
        //var hasMsg = LocalizationManager.Stuff.HasText(this.key);
        //if(!hasMsg)
        //{
        //    return;
        //}
        //string msg = LocalizationManager.Stuff.GetText(this.key);
        this.text.text = msg;
        this.lastLocalizedText = msg;
    }
}